<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import apiOpus from '@/api/modules/opus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

defineOptions({
  name: 'PagesExampleMenuList',
})
const { pagination, getParams, onSizeChange, onCurrentChange } = usePagination()

const router = useRouter()

// 表格是否自适应高度
const tableAutoHeight = ref(false)

// 列表
const loading = ref(false)
const dataList = ref([])
const route = useRoute()

// 作品类型主题映射
const getThemeTitle = (value: string) => {
  const map: Record<string, string> = {
    1: '校徽',
    2: '周边',
  }
  return map[value] || '未知'
}

watch(
  () => route.query.timestamp,
  () => {
    if (route.name === 'PagesExampleMenuList') {
      getDataList()
    }
  },
)

// 搜索
const searchDefault = {
  opusName: '',
  nickName: '',
  themeName: '',
  themeTitle: '',
}
const search = ref({ ...searchDefault })

onMounted(() => {
  if (route.query.themeName) {
    search.value.themeName = route.query.themeName as string
  }
  getDataList()
})

function searchReset() {
  Object.assign(search.value, searchDefault)
}

function getDataList() {
  loading.value = true
  const params = {
    opusName: search.value.opusName,
    nickName: search.value.nickName,
    themeName: search.value.themeName,
    themeTitle: search.value.themeTitle,
    ...(getParams()),
  }
  apiOpus.list(params).then((res: any) => {
    console.log(res)
    loading.value = false
    dataList.value = res.rows
    pagination.value.total = res.total
  })
}

function onCreate(row?: any) {
  router.push({
    name: 'opusCreate',
    query: {
      parentId: row.id,
    },
  })
}

function onView(row: any) {
  router.push({
    name: 'opusReview', // 需要创建对应的详情页面
    params: {
      id: row.opusId,
    },
  })
}

// function onEdit(row: any) {
//   router.push({
//     name: 'opusEdit',
//     params: {
//       id: row.opusId,
//     },
//   })
// }
function onDel(row: any) {
  ElMessageBox.confirm(`确认删除「${row.opusName}」吗？`, '确认信息').then(() => {
    apiOpus.del(Number(row.opusId)).then((res: any) => {
      if (res.code === 200) {
        getDataList()
        ElMessage.success({
          message: '删除成功',
        })
      }
    })
  }).catch(() => {})
}
// 每页数量切换
function sizeChange(size: number) {
  onSizeChange(size).then(() => getDataList())
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList())
}

// 照片预览
function previewImage(url: string) {
  window.open(url, '_blank')
}
</script>

<template>
  <div :class="{ 'absolute-container': tableAutoHeight }">
    <FaPageHeader title="作品管理" class="mb-0" />
    <FaPageMain :class="{ 'flex-1 overflow-auto': tableAutoHeight }" :main-class="{ 'flex-1 flex flex-col overflow-auto': tableAutoHeight }">
      <FaSearchBar :show-toggle="false">
        <template #default>
          <ElForm :model="search" size="default" label-width="80px" inline-message inline class="search-form">
            <ElFormItem label="作品名称">
              <ElInput v-model="search.opusName" placeholder="请输入作品名称" clearable @keydown.enter="currentChange()" @clear="currentChange()" />
            </ElFormItem>

            <!-- 新增用户昵称搜索框 -->
            <ElFormItem label="用户昵称">
              <ElInput v-model="search.nickName" placeholder="请输入用户昵称" clearable @keydown.enter="currentChange()" @clear="currentChange()" />
            </ElFormItem>

            <!-- 新增大赛名称搜索框 -->
            <ElFormItem label="大赛名称">
              <ElInput v-model="search.themeName" placeholder="请输入大赛名称" clearable @keydown.enter="currentChange()" @clear="currentChange()" />
            </ElFormItem>

            <!-- 新增类型下拉框 -->
            <ElFormItem label="作品类型">
              <ElSelect v-model="search.themeTitle" placeholder="请选择作品类型" style="min-width: 178px;" clearable @keydown.enter="currentChange()" @clear="currentChange()">
                <ElOption label="校徽" value="1" />
                <ElOption label="周边" value="2" />
              </ElSelect>
            </ElFormItem>
            <ElFormItem style="margin-left: 10px; flex-shrink: 0;">
              <ElButton @click="searchReset(); currentChange()">
                重置
              </ElButton>
              <ElButton v-auth="'system:opus:list'" type="primary" @click="currentChange()">
                <template #icon>
                  <FaIcon name="i-ep:search" />
                </template>
                筛选
              </ElButton>
            </ElFormItem>
          </ElForm>
        </template>
      </FaSearchBar>
      <ElDivider border-style="dashed" />
      <FaPageMain :class="{ 'flex-1 overflow-auto': tableAutoHeight }" :main-class="{ 'flex-1 flex flex-col overflow-auto': tableAutoHeight }">
        <ElSpace>
          <ElButton v-auth="'system:opus:add'" type="primary" size="default" @click="onCreate">
            <template #icon>
              <FaIcon name="i-ep:plus" />
            </template>
            新增作品
          </ElButton>
        </ElSpace>
        <ElTable v-loading="loading" class="mt-4" :data="dataList" row-key="id" stripe highlight-current-row default-expand-all border height="100%">
          <ElTableColumn prop="nickName" label="用户名称" />
          <ElTableColumn prop="themeName" label="大赛名称" />
          <ElTableColumn prop="opusName" label="作品名称" />
          <ElTableColumn prop="themeTitle" label="作品类型">
            <template #default="scope">
              {{ getThemeTitle(scope.row.themeTitle) }}
            </template>
          </ElTableColumn>
          <ElTableColumn label="作品照片">
            <template #default="scope">
              <div class="table-image-preview">
                <template v-if="scope.row.opusUrl">
                  <img
                    :src="scope.row.opusUrl.split(',')[0]"
                    alt="作品预览"
                    style="max-height: 100px;"
                    @click="previewImage(scope.row.opusUrl.split(',')[0])"
                  >
                </template>
                <div v-else class="empty-image">
                  暂无图片
                </div>
              </div>
            </template>
          </ElTableColumn>
          <!--          <ElTableColumn prop="status" label="审批状态"> -->
          <!--            <template #default="scope"> -->
          <!--              {{ getStatusTitle(scope.row.status) }} -->
          <!--            </template> -->
          <!--          </ElTableColumn> -->
          <ElTableColumn label="操作" width="200" align="center" fixed="right">
            <template #default="scope">
              <ElSpace>
                <!-- 1. 编辑按钮：所有状态，有权限则显示 -->
                <!--                <ElButton -->
                <!--                  v-auth="'system:opus:edit'" -->
                <!--                  type="primary" -->
                <!--                  size="small" -->
                <!--                  plain -->
                <!--                  @click="onEdit(scope.row)" -->
                <!--                > -->
                <!--                  编辑 -->
                <!--                </ElButton> -->

                <!-- 2. 批阅按钮：仅待审核（status=0），有权限则显示 -->
                <!--                <ElButton -->
                <!--                  v-if="scope.row.status === 0" -->
                <!--                  v-auth="'system:opus:status'" -->
                <!--                  type="primary" -->
                <!--                  size="small" -->
                <!--                  plain -->
                <!--                  @click="onReview(scope.row)" -->
                <!--                > -->
                <!--                  批阅 -->
                <!--                </ElButton> -->

                <!-- 3. 查看按钮：已参加/未通过（status≠0）时显示 -->
                <ElButton
                  v-if="scope.row.status === 0"
                  type="primary"
                  size="small"
                  plain
                  @click="onView(scope.row)"
                >
                  查看
                </ElButton>

                <!-- 4. 删除按钮：所有状态，有权限则显示 -->
                <ElButton
                  v-auth="'system:opus:del'"
                  type="primary"
                  size="small"
                  plain
                  @click="onDel(scope.row)"
                >
                  删除
                </ElButton>
              </ElSpace>
            </template>
          </ElTableColumn>
        </ElTable>
        <ElPagination style="margin-top: 20px" :current-page="pagination.page" :total="pagination.total" :page-size="pagination.size" :page-sizes="pagination.sizes" :layout="pagination.layout" :hide-on-single-page="false" class="pagination" background @current-change="currentChange" @size-change="sizeChange" />
      </FaPageMain>
    </fapagemain>
  </div>
</template>

<style scoped>
.absolute-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
.table-image-preview {
  width: 60px;
  height: 60px;
  overflow: hidden;
  border-radius: 4px;
  cursor: pointer;
}

.table-image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
